﻿using System;
using System.Windows.Forms;
using EzDesk.DesktopClient.Command;
using EzDesk.DesktopClient.FunctionWindowModule.ViewContract;
using EzDesk.DesktopClient.FunctionWindowModule.ViewModel;
using WebKit;
using EzDesk.Generic;

namespace EzDesk.DesktopClient.FunctionWindowModule.View
{
    public partial class FunctionFormViewModel : Form, IFunctionPageViewModel
    {
        private readonly WebKitBrowser _webKitBrowser = new WebKitBrowser(true);

        public FunctionFormViewModel()
        {
            InitializeComponent();
        }

        private void WinForm_Load(object sender, EventArgs e)
        {
            CloseBtn.Click += (o, args) => CloseForm();

            _webKitBrowser.Height = 546;
            _webKitBrowser.Dock = DockStyle.Bottom;
            
            Controls.Add(_webKitBrowser);


            _webKitBrowser.DocumentTitleChanged +=
                (o, args) => TitleLbl.Text= _webKitBrowser.DocumentTitle;
            CloseCommand = new DelegateCommand(this.CloseForm);
        }
        private void CloseForm()
        {
            this.OnCloseViewModel.ExecuteMethod(this, null);
            this.Close();
            this._webKitBrowser.Dispose();
            this.Dispose();
        }


        public void Navigate(string url)
        {
            this.Show();
            _webKitBrowser.Navigate(url);

        }

        private string _url;
        public string Url
        {
            get { return _url; }
            set
            {
                _url = value;
                Navigate(_url);
            }
        }


        private const int WM_NCHITTEST = 0x84;
        private const int HTCLIENT = 0x1;
        private const int HTCAPTION = 0x2;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_NCHITTEST:
                    base.WndProc(ref m);
                    if ((int)m.Result == HTCLIENT)
                        m.Result = (IntPtr)HTCAPTION;
                    return;
                    break;
            }
            base.WndProc(ref m);
        } 


        public IFunctionPageView View { get; set; }

        public DelegateCommand CloseCommand { get; set; }

        public event EventHandler OnCloseViewModel;

        public string CallName { get; set; }
        public IFunctionPageViewModel SetCallName(string callName)
        {
            this.CallName = callName;
            return this;
        }
    }
}
